package e.odbo.data.security;

import e.odbo.data.dao.table.TableDefinition;
import e.odbo.data.OdbOContent;
import e.odbo.data.sample.security.I_SecurityFilter;
import e.odbo.data.sample.security.CustomFilterBean;

import java.util.Arrays;

public class DBSecurityFilterBuilder {
    TableDefinition tableDefinition;

    boolean permissionFilterAble = false;
    boolean userFilterAble = false;

    public DBSecurityFilterBuilder(TableDefinition tableDefinition) {
        this.tableDefinition = tableDefinition;
        permissionFilterAble = Arrays.asList(tableDefinition.getFields()).contains(OdbOContent.SECURITY_FIELD_NAME);
        userFilterAble = Arrays.asList(tableDefinition.getFields()).contains(OdbOContent.SECURITY_USER_FIELD_NAME);
    }


    public String andSQL(I_SecurityFilter securityFilter, String alise) {
        return builderFilterString(" and ", securityFilter, alise);
    }

    public String whereSQL(I_SecurityFilter securityFilter, String alise) {
        return builderFilterString(" where ", securityFilter, alise);
    }

    private String builderFilterString(String pref, I_SecurityFilter securityFilter, String alise) {
        String retStr = "";
        if (permissionFilterAble && securityFilter.getSecurityFilter() != null && !securityFilter.getSecurityFilter().isEmpty()) {
            if(alise!=null)
               retStr += alise+"."+ OdbOContent.SECURITY_FIELD_NAME;
            else
                retStr += OdbOContent.SECURITY_FIELD_NAME;
            retStr +=" like " + securityFilter.getSecurityFilter() + "%";
        }
        if (userFilterAble && securityFilter.getUserID() != null && !securityFilter.getUserID().isEmpty()) {
            retStr = retStr.isEmpty() ? retStr : retStr + " and ";
            if(alise!=null)
                retStr += alise+"."+ OdbOContent.SECURITY_USER_FIELD_NAME;
            else
                retStr += OdbOContent.SECURITY_USER_FIELD_NAME;

            retStr += " = " + securityFilter.getUserID();
        }
        CustomFilterBean customFilter = securityFilter.getUserCustomFilter(tableDefinition.getTableName());
        if (customFilter != null) {
            retStr = retStr.isEmpty() ? retStr : retStr + " and ";
            String customFilterStr=customFilter.getValue();
            if(alise==null)
                alise=tableDefinition.getTableName();
            customFilterStr.replaceAll(new String("${alise}"),alise);
            retStr += customFilterStr;
        }
        return retStr.isEmpty()?"":pref + retStr;
        //return retStr.isEmpty()?pref+" 1=1 ":pref + retStr;
    }

}